@file:OptIn(ExperimentalLayoutApi::class)

package com.ljj.bitetime.ui.dialog

import android.annotation.SuppressLint
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.FilterChip
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import com.ljj.bitetime.item.DietaryRestriction
import com.ljj.bitetime.item.Dish
import com.ljj.bitetime.item.IceLevel
import com.ljj.bitetime.item.Options
import com.ljj.bitetime.item.PortionSize
import com.ljj.bitetime.item.SpicyLevel
import com.ljj.bitetime.item.SugarLevel
import com.ljj.bitetime.item.Topping

@Composable
fun DishDetailDialog(
    dish: Dish,
    onDismiss: () -> Unit,
    onAddToCart: (Dish, Int, Options) -> Unit
) {
    var selectedOptions by remember { mutableStateOf(Options()) }
    var quantity by remember { mutableIntStateOf(1) }
    val optionsComplete = isOptionsComplete(dish, selectedOptions)
    Dialog(
        onDismissRequest = onDismiss,
        properties = DialogProperties(usePlatformDefaultWidth = false)
    ) {
        Surface(
            modifier = Modifier
                .fillMaxWidth()
                .fillMaxHeight(0.8f)
                .padding(8.dp),
            shape = RoundedCornerShape(16.dp),
            color = MaterialTheme.colorScheme.primary
        ) {
            Column(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(8.dp)
            ) {
                // 顶部标题栏
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(bottom = 8.dp),
                    horizontalArrangement = Arrangement.SpaceBetween,
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Text(
                        text = dish.name,
                        style = MaterialTheme.typography.titleLarge,
                        fontWeight = FontWeight.Bold,
                        modifier = Modifier.weight(1f)
                    )
                    IconButton(onClick = onDismiss) {
                        Icon(
                            imageVector = Icons.Default.Close,
                            contentDescription = "关闭"
                        )
                    }
                }
                // 中部滚动内容区域
                Column(
                    modifier = Modifier
                        .weight(1f)
                        .background(
                            MaterialTheme.colorScheme.background,
                            RoundedCornerShape(16.dp)
                        )
                        .padding(8.dp)
                        .verticalScroll(rememberScrollState())
                ) {
                    // 菜品描述
                    Text(
                        text = dish.description,
                        style = MaterialTheme.typography.bodyMedium,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                    Spacer(modifier = Modifier.height(16.dp))
                    // 选项选择区域
                    OptionSelection(
                        dish = dish,
                        selectedOptions = selectedOptions,
                        onOptionsChanged = { selectedOptions = it }
                    )
                }
                // 底部操作栏
                BottomActionBar(
                    quantity = quantity,
                    onQuantityChange = { quantity = it },
                    price = calculateTotalPrice(dish, selectedOptions, quantity),
                    enabled = optionsComplete
                ) {
                    onAddToCart(dish, quantity, selectedOptions)
                    onDismiss()
                }
            }
        }
    }
}

@Composable
fun OptionSelection(
    dish: Dish,
    selectedOptions: Options,
    onOptionsChanged: (Options) -> Unit
) {
    // 分量选择
    dish.options.portionSize?.let { _ ->
        OptionSection(
            title = "分量",
            items = PortionSize.entries.map { it.description },
            selectedItem = selectedOptions.portionSize?.description,
            onItemSelected = { description ->
                val selectedPortion = PortionSize.entries.find { it.description == description }
                onOptionsChanged(selectedOptions.copy(portionSize = selectedPortion))
            }
        )
    }
    
    // 辣度选择
    dish.options.spicyLevel?.let { _ ->
        OptionSection(
            title = "辣度",
            items = SpicyLevel.entries.map { it.description },
            selectedItem = selectedOptions.spicyLevel?.description,
            onItemSelected = { description ->
                val selectedSpicy = SpicyLevel.entries.find { it.description == description }
                onOptionsChanged(selectedOptions.copy(spicyLevel = selectedSpicy))
            }
        )
    }
    
    // 糖度选择
    dish.options.sugarLevel?.let { _ ->
        OptionSection(
            title = "糖度",
            items = SugarLevel.entries.map { it.description },
            selectedItem = selectedOptions.sugarLevel?.description,
            onItemSelected = { description ->
                val selectedSugar = SugarLevel.entries.find { it.description == description }
                onOptionsChanged(selectedOptions.copy(sugarLevel = selectedSugar))
            }
        )
    }
    
    // 冰度选择
    dish.options.iceLevel?.let { _ ->
        OptionSection(
            title = "冰度",
            items = IceLevel.entries.map { it.description },
            selectedItem = selectedOptions.iceLevel?.description,
            onItemSelected = { description ->
                val selectedIce = IceLevel.entries.find { it.description == description }
                onOptionsChanged(selectedOptions.copy(iceLevel = selectedIce))
            }
        )
    }
    
    // 加料选择（多选）
    dish.options.toppings?.let { _ ->
        MultiOptionSection(
            title = "加料",
            items = Topping.entries.map { it.description },
            selectedItems = selectedOptions.toppings?.map { it.description } ?: emptyList(),
            onItemToggle = { description ->
                val currentToppings = selectedOptions.toppings?.toMutableList() ?: mutableListOf()
                val topping = Topping.entries.find { it.description == description }
                
                if (topping != null) {
                    if (currentToppings.contains(topping)) {
                        currentToppings.remove(topping)
                    } else {
                        currentToppings.add(topping)
                    }
                    onOptionsChanged(selectedOptions.copy(toppings = currentToppings))
                }
            }
        )
    }
    
    // 忌口选择（多选）
    dish.options.dietaryRestrictions?.let { _ ->
        MultiOptionSection(
            title = "忌口要求",
            items = DietaryRestriction.entries.map { it.description },
            selectedItems = selectedOptions.dietaryRestrictions?.map { it.description } ?: emptyList(),
            onItemToggle = { description ->
                val currentRestrictions = selectedOptions.dietaryRestrictions?.toMutableList() ?: mutableListOf()
                val restriction = DietaryRestriction.entries.find { it.description == description }
                
                if (restriction != null) {
                    if (currentRestrictions.contains(restriction)) {
                        currentRestrictions.remove(restriction)
                    } else {
                        currentRestrictions.add(restriction)
                    }
                    onOptionsChanged(selectedOptions.copy(dietaryRestrictions = currentRestrictions))
                }
            }
        )
    }
}

@Composable
fun OptionSection(
    title: String,
    items: List<String>,
    selectedItem: String?,
    onItemSelected: (String) -> Unit
) {
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = 8.dp)
    ) {
        HorizontalDivider(
            modifier = Modifier
                .fillMaxWidth()
                .padding(vertical = 3.dp),
            thickness = 1.dp,
            color = MaterialTheme.colorScheme.outline
        )
        // 选项标题
        Text(
            text = title,
            style = MaterialTheme.typography.titleMedium,
            fontWeight = FontWeight.Bold,
            modifier = Modifier.padding(bottom = 8.dp)
        )
        // 选项列表
        FlowRow(
            horizontalArrangement = Arrangement.spacedBy(8.dp),
            modifier = Modifier.fillMaxWidth()
        ) {
            items.forEach { item ->
                FilterChip(
                    selected = item == selectedItem,
                    onClick = { onItemSelected(item) },
                    label = {
                        Text(
                            text = item,
                            maxLines = 1,
                            overflow = TextOverflow.Ellipsis,
                            textAlign = TextAlign.Center
                        )
                    }
                )
            }
        }
    }
}

@Composable
fun MultiOptionSection(
    title: String,
    items: List<String>,
    selectedItems: List<String>,
    onItemToggle: (String) -> Unit
) {
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = 8.dp)
    ) {
        Text(
            text = title,
            style = MaterialTheme.typography.titleMedium,
            fontWeight = FontWeight.Bold,
            modifier = Modifier.padding(bottom = 8.dp)
        )
        
        FlowRow(
            horizontalArrangement = Arrangement.spacedBy(8.dp),
            modifier = Modifier.fillMaxWidth()
        ) {
            items.forEach { item ->
                FilterChip(
                    selected = selectedItems.contains(item),
                    onClick = { onItemToggle(item) },
                    label = {
                        Text(
                            text = item,
                            maxLines = 1,
                            overflow = TextOverflow.Ellipsis
                        )
                    }
                )
            }
        }
    }
}

@SuppressLint("DefaultLocale")
@Composable
fun BottomActionBar(
    quantity: Int,
    onQuantityChange: (Int) -> Unit,
    price: Double,
    enabled: Boolean,
    onAddToCart: () -> Unit
) {
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .padding(top = 8.dp),
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            // 数量选择器
            Row(
                verticalAlignment = Alignment.CenterVertically,
                modifier = Modifier
                    .clip(RoundedCornerShape(16.dp))
                    .background(MaterialTheme.colorScheme.background)
            ) {
                IconButton(
                    onClick = { if (quantity > 1) onQuantityChange(quantity - 1) },
                    enabled = quantity > 1
                ) { Text("-") }
                Text(
                    text = quantity.toString(),
                    style = MaterialTheme.typography.bodyLarge,
                    textAlign = TextAlign.Center,
                    modifier = Modifier.width(40.dp)
                )
                IconButton(
                    onClick = { onQuantityChange(quantity + 1) }
                ) { Text("+") }
            }
            // 价格统计
            Text(
                text = "￥${String.format("%.2f", price)}",
                style = MaterialTheme.typography.titleMedium,
                fontWeight = FontWeight.Bold,
                color = MaterialTheme.colorScheme.onPrimary,
                modifier = Modifier.padding(end = 8.dp)
            )
        }
        // 加入购物车按钮
        Button(
            onClick = {
                if (enabled) { onAddToCart() }
            },
            colors = ButtonDefaults.buttonColors(MaterialTheme.colorScheme.background),
            modifier = Modifier.padding(top = 5.dp),
            enabled = enabled
        ) {
            Text(text = "加入购物车")
        }
    }
}

fun calculateTotalPrice(dish: Dish, options: Options, quantity: Int): Double {
    var totalPrice = dish.basePrice
    // 添加分量额外价格
    options.portionSize?.extraPrice?.let { totalPrice += it }
    // 添加加料额外价格
    options.toppings?.forEach { topping ->
        totalPrice += topping.extraPrice
    }
    return totalPrice * quantity
}

fun isOptionsComplete(dish: Dish, selectedOptions: Options): Boolean {
    if (dish.options.portionSize != null && selectedOptions.portionSize == null) return false
    if (dish.options.spicyLevel != null && selectedOptions.spicyLevel == null) return false
    if (dish.options.sugarLevel != null && selectedOptions.sugarLevel == null) return false
    if (dish.options.iceLevel != null && selectedOptions.iceLevel == null) return false
    return true
}